package cn.snailhd.util;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Logger;

public class MutilThreadDownloadManage {
	private static final Logger log = Logger.getLogger(MutilThreadDownloadManage.class.getName());
	
	
	public int getFileSize(String url){		
		HttpRequest request = null;
		try {
			request = new HttpRequest(url);
		} catch (IOException e) {
			e.printStackTrace();
		}
		HttpURLConnection  connection = request.getConnection();
		int realSize = connection.getContentLength();
		return realSize;		
	}
	
	public void  manage(int poolCount,String url,String file){
		
		int size = getFileSize(url);
		System.out.println("size:"+size);
		int average = size/poolCount;
		System.out.println("average:"+average);
		int offset = 0;
		int length=0;
		CountDownLatch end =new CountDownLatch(poolCount);
		
		ExecutorService exec = Executors.newFixedThreadPool(poolCount);
		
		for(int i=0;i<poolCount;i++){
			if(i==(poolCount-1)){
				length = size - (poolCount-1)*average;
			}else {
				length=average;
			}
			
			offset = average*i;			
			exec.execute(new MutilThreadDownload(url, file, offset, length,end));
			
		}
		exec.shutdown();
		try {
			end.await();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
	}
	public static void main(String[] args) {
		String url = "http://v.uzzf.com//fla/FlashCC2015_Setup.zip";
		long begin = System.currentTimeMillis();
		new MutilThreadDownloadManage().manage(4,url,"D:\\hhe3.rar");
		long end = System.currentTimeMillis();
		log.info("end:"+Thread.currentThread().getName()+"   time:"+(end-begin));
	}
	
}
